package com.white.loglib;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;


/**
 * Created by ytf on 2020/7/24 024.
 * Description:
 */
public class LocalSocketPrintStrategy implements LogPrintStrategy
{

    private LogMessagerService logService;
    private Intent logServiceIntent;
    private Context mContext;

    private ServiceConnection sc = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            logService = ((LogMessagerService.MyBinder)service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            logService = null;
        }
    };

    public boolean isConnected(){
        return logService != null && logService.isConnected();
    }

    @Override
    public void init(Context context, Object extra)
    {
        mContext = context;
        logServiceIntent = new Intent(context, LogMessagerService.class);
        context.startService(logServiceIntent);
        context.bindService(logServiceIntent, sc, Context.BIND_AUTO_CREATE);
    }

    @Override
    public boolean isReady()
    {
        return isConnected();
    }

    @Override
    public void print(int level, String log)
    {
        if(logService != null)
        {
            logService.sendMessage(level, log);
        }
    }

    @Override
    public synchronized void destroy()
    {
        if(logService != null)
        {
            mContext.unbindService(sc);
            mContext.stopService(logServiceIntent);
            logService = null;
        }
    }
}
